<?php
/**
 * CSS & Javascript Compressor
 *
 * @version 1.0
 * @author Sergey M. Litvinov (smart@joomlatune.ru), Alexey N. Brin (userxp@joomlaportal.ru)
 * @filename router.class.php
 * @package JoomlaTune Library 
 * @subpackage Optimizer
 * @copyright (C) 2008-2009 by joomlatune.ru
 * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
 * @access public
 * 
 * If you fork this to create your own project, 
 * please make a reference to JoomlaTune Library someplace in your code 
 * and provide a link to http://www.joomlatune.ru
 *
 **/

if( !class_exists( 'JTuneOptimizer' ) ) {
	
	class JTuneOptimizer
	{
		var $head;
		
		/**
		 * Returns a reference to the global JTuneOptimizer object, 
		 * only creating it if it doesn't already exist.
		 *
		 * @static
		 * @param	string $language
		 * @return	JTuneOptimizer $instance
		 */
		function &getInstance() {
			static $instance;
			if (!is_object($instance)) {
				$instance = new JTuneOptimizer();
			}
			return $instance;
		}
		
		function clearJavaScript( $text ) {
			$text = preg_replace('/\/\*.*?\*\//is', '', $text);
			$text = preg_replace('/\t+/is', ' ', $text);
			$text = preg_replace('/(\r\n)+\s?/is', '\\1', $text);
			return $text;
		}
		
		function compress( $files, $type = 'plain' ) {
			$data = '';
			$lastModified = 0;
			
			if (is_array($files)) {
				foreach ($files as $file) {
					if (is_file($file)) {
						$data .= trim(file_get_contents($file));
						
						$modified = filemtime($file);
						if ($modified !== false && $modified > $lastModified) {
							$lastModified = $modified;
						}
					}
				}
				$hash = md5(implode('', $files));
			} else if (is_file($files)) {
				$hash = md5($files);
				$lastModified = filemtime($files);
				$data = trim(file_get_contents($files));
			}
			
			if ('javascript' == $type) {
				$data = $this->clearJavaScript($data);
			}
			
			$encoding = false;
			
			if (empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
				$encoding = false;
			} else {
				if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
					$encoding = 'gzip';
				}
				if (false !== strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip')) {
					$encoding = 'x-gzip';
				}
			}
			
			if (!$encoding || ini_get('zlib.output_compression') || ini_get('output_handler') == 'ob_gzhandler' || !extension_loaded('zlib') || headers_sent()) {
				return $data;
			}
			
			$lastModifiedGMT = gmdate('D, d M Y H:i:s', $lastModified) . ' GMT';
			
			$etag = $hash . '_' . $lastModified;
			
			if (empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
				if (strpos($_SERVER['HTTP_IF_NONE_MATCH'], $etag) !== false) {
					header('Last-Modified: ' . $lastModifiedGMT, true, 304);
					exit();
				}
			}
			
			header('ETag: "' . $etag . '"');
			
			if (empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
				if ($lastModified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
					header("Last-Modified: $lastModifiedGMT", true, 304);
					exit();
				}
			}
			
			header('Content-Encoding: ' . $encoding);
			header('Content-Type: text/' . $type);
			header('Content-Length: ' . strlen($data));
			header('Last-Modified: ' . $lastModifiedGMT);
			
			$data = gzencode($data, 9);
			echo $data;
			exit();
		}
		
		
		
		
		
		
		
		/**************************************************/
		// EXPERIMENTAL //
		
		function store( $kind, $options=null, $pos=null ) {
			
			$jto = &JTuneOptimizer::getInstance();
			if( !is_array( $jto->head ) ) {
				$jto->head = new array();
			}
			if( $kind ) {
				if( !$jto->head->$kind ) $jto->head->$kind = new array();
				$obj = & $jto->head->$kind;
				$line = JTuneOptimizer::_getScrArr( $kind, $options );
				
				$cnt = count( $obj );
				if( $cnt==0 ) {
					$obj[] = $line;
				} else {
					if( $pos === null || $pos > $cnt ) $pos = $cnt;
					
					$new_array = new array();
					foreach( $obj as $k=>$o ) {
						if( $k==$pos ) $new_array[] = $line;
						$new_array[] = $o;
					}
					
					$obj = $new_array;
				}
			}
		} //store
		
		function _getScrArr( $type='', $options=null ) {
			
			if( !is_array( $options ) ) {
				$options = new array();
			}
			
			switch( $type ) {
				//case 'css':
				case 'link':
					$options['start_tag']	= 'link';
					$options['end_tag']		= '';
					$options['rel']			= 'stylesheet';
					$options['type']		= 'text/css';
				break;
				//case 'js':
				case 'script':
					$options['start_tag']	= 'script';
					$options['end_tag']		= 'script';
					$options['type']		= 'text/javascript';
				break;
				case 'meta':
					$options['start_tag']	= 'meta';
					$options['end_tag']		= '';
					if( isset( $options['text'] ) ) {
						$options['content']	= $options['text'];
						unset( $options['text'] );
					}
				break;
				case 'title':
					$options['start_tag']	= 'title';
					$options['end_tag']		= 'title';
				break;
				default:
					$options = new array();
				break;
			}
			return $options;
		} //_getScrArr
		
		function parseLine( $arr ) {
			
			if( !$arr['start_tag'] ) return '';
			
			$start = '<'.$arr['start_tag'];
			
			if( $arr['end_tag'] ) {
				$stop = '>'.$arr['text'].'</'.$arr['end_tag'].'>';
			} else {
				$stop = ' />';
			}
			
			unset($arr['start_tag']);
			unset($arr['text']);
			unset($arr['end_tag']);
			
			foreach( $arr as $key=>$value ) {
				$start .= ' '.$key.'="'.$value.'"';
			}
			
			return $start.$stop;
			
		} //parseLine
		
		function sendToHead() {
			$jto = &JTuneOptimizer::getInstance();
			if( is_array( $jto->head ) ) {
				
				$app = &JTuneConfig::getApplication();
				$vars = array( 'title', 'meta', 'link', 'script' );
				
				foreach( $vars as $v ) {
					if( count( @$jto->head->$v ) ) {
						foreach( $jto->head->$v as $line ) {
							$code = JTuneOptimizer::parseLine( $line );
							$app->addCustomHeadTag( $code );
						}
					}
				}
			}
		}
		
		
		function &getHead() {
			if( class_exists( 'JFactory' ) ) {
				$document=& JFactory::getDocument();
				$head =& $document->_custom;
			} else {
				$app = &JTuneConfig::getApplication();
				$head =& $app->_head['custom'];
			}
			return $head;
		}
		
		function _() {
			$head = JTuneOptimizer::getHead();
			$code = implode( '', $head );
			
			$code = JTuneOptimizer::getJS( $code );
			//$code = implo( $code );
			//$code = htmlentities( $code );
			return $code;
		}
		
		function getJS( $string='' ) {
			$pt1 = "%<script[^>]*(src=\".*\")?>([^>]*)</script>%si";
			$pt2 = "%src=\"(.*?)\"%i";
			preg_match_all( $pt1, $string, $matches );
			foreach( $matches[0] as $key=>$m ) {
				if( ! @$matches[2][$key] ) {
					preg_match( $pt2, $m, $mt );
					if( count( $mt ) ) {
						$matches[2][$key] = $mt[1];
					}
					//xdump( $mt );
				}
				
				//xdump( $matches[2][$key] );
			}
			return $matches;
		}
		
		function getCSS( $string='' ) {
			
		}
	}
}

?>